#include <cstring>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>

const int LENGTH = 4096;

void read_from_maped_file(int fd)
{
    char buff[LENGTH]; buff[0] = '\0';
    char* addr = (char*)mmap(nullptr, LENGTH, PROT_READ, MAP_SHARED, fd, 0);
    memcpy(buff, addr, sizeof(buff));
    std::cout << "get a msg from mm_file:\n" << buff << std::endl;
}

void write_to_maped_file(int fd, const char* msg)
{
    char* addr = (char*)mmap(nullptr, LENGTH, PROT_WRITE, MAP_SHARED, fd, 0);
    int len = strlen(msg);
    ftruncate(fd, len);
    mempcpy(addr, msg, len);
    msync(addr, LENGTH, MS_SYNC);
    std::cout << "send a msg to mm_file..." << std::endl;
    munmap(addr, LENGTH);
}

int main()
{
    int fd = open("txt", O_RDWR);

    const char* msg = "hello linux!";
    write_to_maped_file(fd, msg);
    read_from_maped_file(fd);

    close(fd);
    return 0;
}